<template>
	<view class="container">
		<view class="header">
			<text class="header-title">选择角色</text>
			<text class="header-subtitle">请选择需要测试的角色（可多选）</text>
		</view>
		
		<scroll-view class="content" scroll-y>
			<view v-if="isLoading" class="loading-container">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>
			
			<view v-else-if="loadError" class="error-container">
				<text class="error-text">加载失败，请点击重试</text>
				<button class="retry-btn" @click="loadCharacters">重试</button>
			</view>
			
			<view v-else class="characters-grid">
				<view
					v-for="character in characters"
					:key="character._id"
					class="character-card"
					:class="{ 'selected': selectedCharacters.includes(character._id) }"
					@click="toggleCharacter(character._id)"
				>
					<image class="character-avatar" :src="character.avatar" mode="aspectFill"></image>
					<view class="character-info">
						<text class="character-name">{{ character.name }}</text>
						<text class="character-age">{{ character.age }}</text>
						<text class="character-personality">{{ character.personality }}</text>
					</view>
					<view class="select-indicator">
						<view class="checkbox" :class="{ 'checked': selectedCharacters.includes(character._id) }">
							<text v-if="selectedCharacters.includes(character._id)" class="checkbox-icon">✓</text>
						</view>
					</view>
				</view>
			</view>

			<view class="start-test-container">
				<button 
					class="start-btn" 
					:class="{ 'disabled': selectedCharacters.length === 0 }"
					@click="startTest"
				>
					开始测本
				</button>
			</view>

			<!-- 历史测本列表 -->
			<view class="history-section">
				<text class="history-title">历史测本</text>
				<view class="history-list">
					<view v-if="isHistoryLoading" class="loading-container">
						<view class="loading-spinner"></view>
						<text class="loading-text">加载中...</text>
					</view>
					<view v-else-if="historyLoadError" class="error-container">
						<text class="error-text">加载失败，请点击重试</text>
						<button class="retry-btn" @click="loadHistoryTests">重试</button>
					</view>
					<view v-else class="history-items">
						<view v-for="test in historyTests" :key="test._id" class="history-item" @click="goToTest(test._id)">
							<view class="history-item-main">
								<text class="history-item-name">{{ test.script_name }}</text>
								<text class="history-item-time">{{ formatDate(test.start_time) }}</text>
							</view>
							<text class="history-item-status" :class="getStatusClass(test.status)">{{ getStatusText(test.status) }}</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		

	</view>
</template>

<script>
	export default {
		data() {
			return {
				selectedCharacters: [],
				characters: [],
				isLoading: false,
				loadError: false,
				historyTests: [],
				isHistoryLoading: false,
				historyLoadError: false
			}
		},
		onLoad() {
			this.loadCharacters()
			this.loadHistoryTests()
		},
		methods: {
			async loadCharacters() {
				this.isLoading = true
				this.loadError = false
				try {
					const db = uniCloud.database()
					console.log('开始查询数据库...')
					const res = await db.collection('script_player').limit(1000).get()
					console.log('查询结果:', res)
					if (res.result && res.result.data && res.result.data.length > 0) {
						this.characters = res.result.data
						console.log('成功获取角色数据:', this.characters)
					} else {
						console.error('未找到角色数据')
						this.loadError = true
						uni.showToast({
							title: '暂无角色数据',
							icon: 'none'
						})
					}
				} catch (e) {
					console.error('加载角色数据失败:', e)
					this.loadError = true
					uni.showToast({
						title: `加载失败: ${e.message || '未知错误'}`,
						icon: 'none',
						duration: 2000
					})
				} finally {
					this.isLoading = false
				}
			},
			toggleCharacter(id) {
				const index = this.selectedCharacters.indexOf(id)
				if (index === -1) {
					this.selectedCharacters.push(id)
				} else {
					this.selectedCharacters.splice(index, 1)
				}
			},
			async startTest() {
				if (this.selectedCharacters.length === 0) return
				
				uni.showModal({
					title: '输入剧本名称',
					editable: true,
					placeholderText: '请输入剧本名称',
					success: async (res) => {
						if (res.confirm && res.content) {
							try {
								console.log('开始创建测试记录...');
								console.log('选中的角色ID:', this.selectedCharacters);
								
								// 获取选中角色的详细信息
								const selectedPlayers = this.characters.filter(char => 
									this.selectedCharacters.includes(char._id)
								).map(char => ({
									player_id: char._id,
									name: char.name,
									avatar: char.avatar
								}))
								
								console.log('处理后的角色数据:', selectedPlayers);
								
								// 创建测试记录
								const db = uniCloud.database();
								const currentTime = Date.now(); // 使用时间戳
								console.log('当前时间:', new Date(currentTime));
								
								const testData = {
									selected_players: selectedPlayers,
									script_name: res.content,
									start_time: currentTime,
									status: 0, // 进行中
									create_date: currentTime
								};
								console.log('准备提交的数据:', testData);
								
								const result = await db.collection('script_test').add(testData);
								console.log('数据库添加结果:', result);
								
								if (result.result && result.result.id) {
									// 跳转到剧本测试页面并传递测试记录ID
									uni.navigateTo({
										url: `/pages/script_test/script_test_begin?testId=${result.result.id}`
									})
								} else {
									throw new Error('创建测试记录失败')
								}
							} catch (e) {
								console.error('创建测试记录失败:', e)
								uni.showToast({
									title: '创建测试记录失败，请重试',
									icon: 'none'
								})
							}
						} else {
							uni.showToast({
								title: '请输入剧本名称',
								icon: 'none'
							})
						}
					}
				})
			},
			async loadHistoryTests() {
				this.isHistoryLoading = true
				this.historyLoadError = false
				try {
					const db = uniCloud.database()
					const res = await db.collection('script_test')
						.orderBy('create_date', 'desc')
						.limit(10)
						.get()
					
					if (res.result && res.result.data) {
						this.historyTests = res.result.data
					} else {
						this.historyLoadError = true
					}
				} catch (e) {
					console.error('加载历史测本失败:', e)
					this.historyLoadError = true
					uni.showToast({
						title: `加载失败: ${e.message || '未知错误'}`,
						icon: 'none',
						duration: 2000
					})
				} finally {
					this.isHistoryLoading = false
				}
			},
			formatDate(timestamp) {
				const date = new Date(timestamp)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
			},
			getStatusText(status) {
				switch (status) {
					case 0: return '进行中'
					case 1: return '已完成'
					case 2: return '已中断'
					default: return '未知状态'
				}
			},
			getStatusClass(status) {
				switch (status) {
					case 0: return 'status-ongoing'
					case 1: return 'status-completed'
					case 2: return 'status-interrupted'
					default: return ''
				}
			},
			goToTest(testId) {
				uni.navigateTo({
					url: `/pages/script_test/script_test_begin?testId=${testId}`
				})
			},
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		position: relative;
	}
	
	.container::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)), url('/static/bg.png') no-repeat center center;
		background-size: cover;
		z-index: -1;
	}
	
	.header {
		padding: 60rpx 40rpx;
		text-align: center;
	}
	
	.header-title {
		font-size: 48rpx;
		color: #ffffff;
		font-weight: bold;
		margin-bottom: 20rpx;
	}
	
	.header-subtitle {
		font-size: 28rpx;
		color: rgba(255, 255, 255, 0.8);
	}
	
	.content {
		padding: 30rpx;
		height: calc(100vh - 200rpx);
	}

	.history-section {
		margin-top: 40rpx;
		padding: 20rpx;
		background: rgba(0, 0, 0, 0.3);
		border-radius: 20rpx;
	}

	.history-title {
		font-size: 36rpx;
		color: #ffffff;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.history-list {
		padding: 10rpx;
	}

	.history-items {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}

	.history-item {
		background: rgba(255, 255, 255, 0.1);
		border-radius: 15rpx;
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		transition: all 0.3s ease;
	}

	.history-item:active {
		background: rgba(255, 255, 255, 0.2);
	}

	.history-item-main {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.history-item-name {
		font-size: 32rpx;
		color: #ffffff;
		font-weight: bold;
	}

	.history-item-time {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.6);
	}

	.history-item-status {
		font-size: 26rpx;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
	}

	.status-ongoing {
		background: rgba(64, 158, 255, 0.2);
		color: #409EFF;
	}

	.status-completed {
		background: rgba(103, 194, 58, 0.2);
		color: #67C23A;
	}

	.status-interrupted {
		background: rgba(245, 108, 108, 0.2);
		color: #F56C6C;
	}
	
	.characters-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(240rpx, 1fr));
		gap: 20rpx;
		padding-bottom: 120rpx;
	}
	
	.character-card {
		background: rgba(255, 255, 255, 0.15);
		border-radius: 20rpx;
		padding: 20rpx;
		position: relative;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}
	
	.character-card.selected {
		background: rgba(255, 255, 255, 0.25);
		box-shadow: 0 2rpx 15rpx rgba(255, 255, 255, 0.2);
	}
	
	.character-avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		margin-bottom: 15rpx;
	}
	
	.character-info {
		padding-right: 40rpx;
	}
	
	.character-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #ffffff;
		display: block;
		margin-bottom: 8rpx;
	}
	
	.character-personality {
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.8);
		display: block;
	}
	
	.character-age {
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.9);
		display: block;
		margin-bottom: 8rpx;
	}
	
	.select-indicator {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
	}
	
	.checkbox {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid rgba(255, 255, 255, 0.5);
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.checkbox.checked {
		background: rgba(255, 255, 255, 0.9);
		border-color: rgba(255, 255, 255, 0.9);
	}
	
	.checkbox-icon {
		color: #000000;
		font-size: 28rpx;
	}
	
	.loading-container,
	.error-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100%;
	}
	
	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid rgba(255, 255, 255, 0.3);
		border-top-color: #ffffff;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}
	
	@keyframes spin {
		to { transform: rotate(360deg); }
	}
	
	.loading-text,
	.error-text {
		color: #ffffff;
		font-size: 28rpx;
		margin-top: 20rpx;
	}
	
	.retry-btn {
		margin-top: 30rpx;
		background: rgba(255, 255, 255, 0.2);
		color: #ffffff;
		border: 2rpx solid rgba(255, 255, 255, 0.5);
		border-radius: 30rpx;
		padding: 10rpx 40rpx;
		font-size: 28rpx;
	}
	
	.start-test-container {
		padding: 40rpx 0;
		display: flex;
		justify-content: center;
	}
	
	.start-btn {
		background: rgba(255, 255, 255, 0.9);
		color: #000000;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		font-size: 32rpx;
		font-weight: bold;
		transition: all 0.3s ease;
		width: 300rpx;
	}
	
	.start-btn.disabled {
		background: rgba(255, 255, 255, 0.3);
		color: rgba(255, 255, 255, 0.5);
	}
	
	/* 适配H5端 */
	@media screen and (min-width: 768px) {
		.characters-grid {
			grid-template-columns: repeat(auto-fill, minmax(400rpx, 1fr));
			max-width: 1200rpx;
			margin: 0 auto;
		}
	}
</style>